<template>
  <div class="app main">
    <div class="title">用户管理</div>
    <div class="headerInput">
      <a-form layout="inline" style="width:100%">
        <a-form-item label="Find" class="searchInputBox">
          <a-input placeholder v-model.trim="searchText" class="searchInput" allowClear />
        </a-form-item>
        <a-form-item class="ml300">
          <a-button type="primary" @click="search">Search</a-button>
        </a-form-item>
        <a-form-item class="ml50">
          <a-button type="primary" @click="add">Add</a-button>
        </a-form-item>
        <!-- <a-form-item class="ml50">
          <a-button type="primary" @click="Export">Download template</a-button>
        </a-form-item>-->
        <a-form-item class="ml50">
          <a-button type="primary" @click="Export">upload</a-button>
        </a-form-item>
        <!-- <a-form-item class="ml50">
          <fileUpload></fileUpload>
        </a-form-item>-->
      </a-form>
    </div>
    <div class="tableSection">
      <a-table :data-source="tableData" :customRow="clickKindTable" :pagination="false">
        <a-table-column key="NTID" title="NTID" data-index="NTID" />
        <a-table-column key="UserName" title="UserName" data-index="UserName" />
        <a-table-column key="Role" title="Role" data-index="RoleName" />
        <a-table-column key="Phone" title="Phone" data-index="Phone" />
        <a-table-column key="Email" title="Email" data-index="Email" />
        <a-table-column key="IsEnabled" title="IsEnabled" data-index="IsEnabled" />
        <a-table-column key="IsSME" title="IsSME" data-index="IsSME" />
        <a-table-column key="CreateTime" title="CreateTime" data-index="CreateTime" />
        <a-table-column key="action" title="Action">
          <template slot-scope="text, record">
            <span>
              <a-button type="primary" @click="editMoudule(text,record)">Edit</a-button>
              <a-button
                type="primary"
                style="margin-left:10px;"
                @click="delMoudule(text,record)"
              >Delete</a-button>
              <a-button
                type="primary"
                style="margin-left:10px;"
                @click="resetPwd(text,record)"
              >ResetPassword</a-button>
            </span>
          </template>
        </a-table-column>
      </a-table>

      <a-pagination
        v-model="currentPage"
        show-size-changer
        show-quick-jumper
        :page-size.sync="pageSize"
        :total="totalCount"
        @showSizeChange="changePage"
        @change="changePage"
        class="pagination"
      />
    </div>
    <!--  新增编辑弹窗部分 -->
    <a-modal
      v-model="moudelVisible"
      :title="ModalTitle"
      @ok="handleOk"
      @cancel="cancleSubmit"
      :maskClosable="true"
      :destroyOnClose="true"
    >
      <div>
        <a-form :label-col="labelCol" :wrapper-col="wrapperCol">
          <a-form-item label="NTID">
            <a-input :disabled="doType==='add'?false:true" placeholder v-model.trim="NTID" />
          </a-form-item>
          <a-form-item label="UserName">
            <a-input placeholder v-model.trim="UserName" allowClear />
          </a-form-item>

          <a-form-item label="Department">
            <a-select @change="DepartmentChange" :default-value="DeptName" allowClear>
              <a-select-option
                v-for="(item, index) in DepartmentInfo"
                :key="index"
                :value="item.DeptId"
              >{{ item.DeptName }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="Role">
            <a-select @change="RoleChange" v-model="RoleId" allowClear>
              <a-select-option
                v-for="(item, index) in RoleInfo"
                :key="index"
                :value="item.RoleId "
              >{{ item.RoleName }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="Phone">
            <a-input placeholder v-model.trim="Phone" allowClear />
          </a-form-item>
          <a-form-item label="Email">
            <a-input placeholder v-model.trim="Email" allowClear />
          </a-form-item>
          <a-form-item label>
            <div>
              <a-checkbox class="ml55 inline" @change="checkIsSME">Is SME</a-checkbox>
              <a-checkbox
                class="ml55 inline"
                @change="checkIsEnadble"
                v-model="isCheckAbled"
              >IsEnabled</a-checkbox>
            </div>
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
    <a-modal
      v-model="isExportVisible"
      :title="ModalTitle"
      :maskClosable="true"
      @ok="()=>isExportVisible=false"
      :destroyOnClose="true"
    >
      <div>
        <a-form :label-col="labelCol" :wrapper-col="wrapperCol">
          <a-form-item label="Upload">
            <fileUpload
              :fileType="'application/vnd.ms-excel'"
              :httpUrl="'/api/UserImport'"
              @getUploadInfo="getUploadInfo"
              :PropData="PropData"
            ></fileUpload>
          </a-form-item>
          <a-form-item label="Template">
            <a-button type="primary" @click="Download">Download Template</a-button>
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
  </div>
</template>

<script>
import userApi from '@/public/httpApi/user'
import fileUpload from '@/components/upload/CommonUploadFile'

export default {
  data() {
    return {
      searchText: '',
      tableData: [],
      totalCount: 0,
      currentPage: 1,
      pageSize: 20,
      NTID: '',
      UserName: '',
      IsSME: 0,
      RoleId: '',
      Phone: '',
      Email: '',
      ModalTitle: '',
      IsEnabled: 1, //0 不可用 1 可用
      Role: '',
      RoleInfo: [],
      doType: '',
      moudelVisible: false,
      isCheckAbled: true,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
      },
      DepartmentInfo: [],
      DeptId: '',
      defaultDeptName: '',
      defaultRoleName: '',
      DeptName: '',
      RoleName: '',
      passWord: '',
      sortNum: 1,
      isExportVisible: false,
      PropData: {},
    }
  },
  watch: {
    IsEnabled() {},
    searchText() {
      this.debounce()
    },
  },
  created() {
    this.getTableData()
    this.getDepartmentInfo()
    this.getRoleInfo()
    this.PropData.NTID = sessionStorage.getItem('userId')
  },
  components: {
    fileUpload,
  },
  methods: {
    getUploadInfo(e) {
      console.log('e :>> ', e)
      if (e.file.response.code == 0) {
        this.$message.success('Upload Success!')
      }
      this.getTableData()
    },

    Export() {
      this.ModalTitle = 'User document upload'
      this.isExportVisible = true
    },
    Download() {
      let url = 'http://10.114.20.142:7099/UserImportModel.xls'
      window.open(url, 'pdf', 'height=698, width=1200,left=298,top=100')
    },
    resetPwd(item, index) {
      const that = this
      this.NTID = item.NTID
      const a = {
        NTID: item.NTID,
      }
      console.log('reset :>> ', item)
      this.$confirm({
        title: 'warm prompt',
        content: 'Do you want to Reset this user password?',
        onOk() {
          userApi.resetUserPassword(a).then((result) => {
            console.log('result :>> ', result)
            if (result.code === 0) {
              that.$message.success(
                `The default password ${result.data[0].DefaultPassword} has been reset!`
              )
            }
          })
          that.debounce()
        },
      })
    },
    debounce() {
      setTimeout(() => {
        this.getTableData()
      }, 800)
    },
    cancleSubmit() {
      this.DeptName = ''
      this.DeptId = ''
      this.RoleName = ''
      this.RoleId = ''
    },
    getDepartmentInfo() {
      let data = {}
      const a = {
        method: 'SysDept_Que',
        userId: window.userId || 1,
        sign: '1',
        currentPage: this.currentPage,
        queMode: 'OR',
        limit: this.pageSize,
        datas: data,
      }
      this.$post(a).then((result) => {
        this.DepartmentInfo = result.data.length > 0 ? result.data : []
        this.DepartmentInfo.map((item) => {
          item.CreateTime = item.CreateTime.replace('T', ' ').split('.')[0]
          return item
        })
      })
    },
    getRoleInfo() {
      const a = {
        method: 'SysRole_Que',
        userId: window.userId || 1,
        sign: '1',
        currentPage: this.currentPage,
        queMode: 'OR',
        limit: this.pageSize,
        datas: {},
      }
      this.$post(a).then((result) => {
        if (result.data.length > 0) {
          this.RoleInfo = result.data
        }
      })
    },
    DepartmentChange(value, e) {
      this.DeptId = value
      console.log('value,e :>> ', value, e)
    },
    sectorChange() {},
    // 查询
    getTableData() {
      const that = this
      let data = this.searchText
        ? {
            UserName: '%' + this.searchText + '%',
            NTID: '%' + this.searchText + '%',
            DeptName: '%' + this.searchText + '%',
            RoleName: '%' + this.searchText + '%',
            Phone: '%' + this.searchText + '%',
            Email: '%' + this.searchText + '%',
          }
        : {}
      const a = {
        method: 'SysUser_Que',
        userId: window.userId || 1,
        sign: '1',
        queMode: 'OR',
        currentPage: this.currentPage,
        limit: this.pageSize,
        orderByList: 'NTID',
        datas: data,
      }
      that.$post(a).then((result) => {
        this.$nextTick(() => {
          if (result.data.length > 0) {
            that.tableData = result.data
            that.totalCount = result.count
            that.tableData.map((item) => {
              item.IsSME = item.IsSME.toString()
              item.IsEnabled = item.IsEnabled.toString()
              item.CreateTime = item.CreateTime.replace('T', ' ').split('.')[0]
              return item
            })
          } else {
            that.tableData = []
          }
        })
      })
    },
    checkIsEnadble(e) {
      this.IsEnabled = e.target.checked === true ? 1 : 0
      console.log('e :>> ', this.IsEnabled)
    },
    checkIsSME(e) {
      this.IsSME = e.target.checked === true ? 1 : 0
      console.log('e :>> ', e)
    },
    RoleChange(value, e) {
      this.RoleId = value
      console.log('RoleChange :>> ', value)
    },
    search() {
      this.currentPage = 1

      this.getTableData()
    },
    add() {
      this.doType = 'add'
      // 清空参数
      this.CreateBy = ''
      this.CreateTime = ''
      this.Email = ''
      this.IsSME = 0
      this.NTID = ''
      this.Phone = ''
      this.Role = ''
      this.RoleId = ''
      this.UserName = ''
      this.ModalTitle = 'Add User'
      this.passWord = ''
      this.moudelVisible = true
    },
    clickKindTable(record, index) {
      return {
        on: {
          click: () => {},
        },
      }
    },
    // 编辑模组
    editMoudule(item, index) {
      this.doType = 'edit'
      this.ModalTitle = 'Edit User'
      this.ModuleTipIndex = index
      console.log('item :>> ', item)
      this.CreateBy = item.CreateBy
      this.CreateTime = item.CreateTime
      this.Email = item.Email
      this.IsEnabled = item.IsEnabled
      this.IsSME = item.IsSME
      this.NTID = item.NTID
      this.Phone = item.Phone
      this.UserName = item.UserName
      this.RoleName = item.RoleName
      this.RoleId = item.RoleId
      this.DeptId = item.DeptId
      this.DeptName = item.DeptName
      this.passWord = item.UserPwd
      this.$forceUpdate()
      this.moudelVisible = true
    },
    //删除模组
    delMoudule(item, index) {
      console.log(item, 'del')
      const that = this
      this.doType = 'del'
      const a = {
        method: 'SysUser_Del',
        userId: window.userId || 1,
        sign: '1',
        currentPage: 0,
        limit: 0,
        datas: {
          NTID: item.NTID,
        },
      }
      this.$confirm({
        title: 'warm prompt',
        content: 'Do you want to Delete this data?',
        onOk() {
          that.$post(a).then((result) => {
            if (result.code == 0) {
              that.$message.success('successfully delete!')
              that.getTableData()
            }
          })
        },
        onCancel() {},
      })
    },
    changePage(current, pageSize) {
      this.currentPage = current
      this.pageSize = pageSize
      this.getTableData()
    },

    addInfo() {
      const a = {
        method: 'SysUser_Add',
        userId: window.userId || 1,
        sign: '1',
        currentPage: 0,
        limit: 0,
        datas: {
          NTID: this.NTID,
          // UserPwd: this.passWord,
          UserName: this.UserName,
          IsSME: this.IsSME,
          RoleId: this.RoleId,
          Phone: this.Phone,
          Email: this.Email,
          IsEnabled: this.IsEnabled,
          DeptId: this.DeptId,
        },
      }
      this.$post(a).then((result) => {
        if (result.code == 0) {
          this.$message.success('Add successfully!')
          this.getTableData()
        }
      })
    },
    editInfo() {
      const a = {
        method: 'SysUser_Mod',
        userId: window.userId || 1,
        sign: '1',
        currentPage: 0,
        limit: 0,
        datas: {
          NTID: this.NTID,
          // UserPwd: this.passWord,
          UserName: this.UserName,
          IsSME: this.IsSME,
          RoleId: this.RoleId,
          Phone: this.Phone,
          Email: this.Email,
          IsEnabled: this.IsEnabled,
          DeptId: this.DeptId,
        },
      }
      this.$post(a).then((result) => {
        // console.log(result, '修改完成')
        if (result.code == 0) {
          this.$message.success('updated successfully!')
          this.getTableData()
        }
      })
    },
    handleOk() {
      if (!this.NTID) {
        this.$message.warn('Please enter the NTID')
        return
      } else if (!this.UserName) {
        this.$message.warn('Please enter the user name')
        return
      } else if (!this.RoleId) {
        this.$message.warn('Please Select the Role')
        return
      } else if (!this.DeptId) {
        this.$message.warn('Please Select the Department')
        return
      } else if (this.Email && !/^\S+@\S+\.\S{2,}$/.test(this.Email)) {
        this.$message.warn('Please enter the correct email address')
        return
      }
      if (this.doType === 'edit') {
        this.editInfo()
      } else if (this.doType === 'add') {
        this.addInfo()
      }
      this.moudelVisible = false
    },
  },
}
</script>

<style lang="less" scoped>
.inline {
  display: inline-block;
}
.main {
}
.headerInput {
  display: flex;
  width: 100%;
  align-items: center;
  .searchInputBox {
    input {
      width: 280px;
    }
  }
  .ml300 {
    margin-left: 180px;
  }
  .ml50 {
    margin-left: 28px;
  }
}
.tableSection {
  margin-top: 30px;
  clear: both;
}
.pagination {
  margin-top: 38px;
  position: absolute;
  right: 100px;
}
.app {
  background: white;
}

.ml55 {
  margin-left: 76.8px;
}
</style>